//
//  BookHomeViewController.m
//  TuDianEducation
//
//  Created by lixinkeji on 2021/1/6.
//  Copyright © 2021 zhangbenchao. All rights reserved.
//


#import "BookHomeViewController.h"
#import "BkGoodsDetailViewController.h"
#import "BkAgeListViewController.h"
#import "LXMessageViewController.h"
#import "DSSearchViewController.h"

#import "BkGoodsCollectionViewCell.h"
#import "BkMovieSelectView.h"

#import "LXMarketGoodsListModel.h"
#import "LXSaveUserInforTool.h"

#import "BkHomePageView.h"

@interface BookHomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITextFieldDelegate>{
    CGFloat left;
    CGFloat space;
    
}
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,assign) NSInteger row;
@property (nonatomic,strong) UIImageView *bigImgView;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic,strong) BkHomePageView *headerView;

@property (nonatomic,strong) UITextField *searchTextFiled;
@property (nonatomic,strong) UIImageView *searchImg;
///banner
@property (nonatomic,strong) NSArray *bannerArray;
///一级分类
@property (nonatomic,strong) NSArray *classify1Array;
///二级分类
@property (nonatomic,strong) NSArray *classify2Array;

@property (nonatomic,strong) UIButton *messageBtn;
@end

@implementation BookHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.row = 2;
    [self.view addSubview:self.collectionView];
   
    //[self.collectionView.mj_header beginRefreshing];
    self.view.backgroundColor = kSubBacColor;
    
    
    
    [self navigationConfig];
    
    
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self urlHttpRequst];
    self.tabBarController.tabBar.hidden = NO;
}
-(void)urlHttpRequst
{
    [self getclassify1listRqust];
    [self gettuiclassify2listRqust];
    [self requstBannerRqust];
    [self headerRefresh];
    [self requstUnreadCount];
}
-(void)navigationConfig{
    self.navigationItem.titleView = self.searchTextFiled;
  //  [self addRightNavgationItemWithImage:[UIImage imageNamed:@"wuxiaoxi"]];
 //   UIButton *messageBtn = [TSWLTools allocButtonTitle:@"" font:systemFont(TSScaleW(0)) textColor:kWhiteColor image:[UIImage imageNamed:@"wuxiaoxi"] frame:CGRectMake(0, 0, TSScaleW(40), TSScaleW(40)) sel:@selector(messageAction:) taget:self];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, TSScaleW(28), TSScaleW(28))];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, TSScaleW(28), TSScaleW(28))];
    imageView.image = [UIImage imageNamed:@"logo"];
    [view addSubview:imageView];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:view];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.messageBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

-(UIButton *)messageBtn{
    if (!_messageBtn) {
        _messageBtn = [TSWLTools allocButtonTitle:@"" font:systemFont(TSScaleW(0)) textColor:kWhiteColor image:[UIImage imageNamed:@"wuxiaoxi"] frame:CGRectMake(0, 0, TSScaleW(40), TSScaleW(40)) sel:@selector(messageAction:) taget:self];
    }
    return _messageBtn;
}
-(void)messageAction:(UIButton *)sender
{
    LXMessageViewController *vc = [[LXMessageViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark ---个人信息事件
-(void)leftBtnAction:(id)sender{
    
}
#pragma mark --消息事件
-(void)rigthBtnAction:(id)sender{
    
}
-(UITextField *)searchTextFiled{
    if (!_searchTextFiled) {
        _searchTextFiled = [TSWLTools allocTextFieldTextFont:TSScaleW(14) placeHolderFont:TSScaleW(14) text:nil placeText:@"请输入商品名称进行搜索" textColor:kMainTxtColor placeHolderTextColor:kGrayTxtColor frame:CGRectMake(TSScaleW(12), TSScaleW(10),TSScaleW(260), TSScaleW(27))];
        _searchTextFiled.cornerRadius = _searchTextFiled.height/2.f;
        _searchTextFiled.leftViewMode = UITextFieldViewModeAlways;
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, TSScaleW(34), _searchTextFiled.height)];
        [view addSubview:self.searchImg];
        _searchTextFiled.leftView = view;
        _searchTextFiled.backgroundColor = kMainBgColor;
        _searchTextFiled.delegate = self;
        UIButton *seachBtn = [TSWLTools allocButtonTitle:@"" font:systemFont(0) textColor:kWhiteColor image:nil frame:_searchTextFiled.bounds sel:@selector(searchAction) taget:self];
        [_searchTextFiled addSubview:seachBtn];
    }
    return _searchTextFiled;
}
-(void)searchAction
{
    DSSearchViewController *vc = [[DSSearchViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
-(UIImageView *)searchImg{
    if (!_searchImg) {
        _searchImg = [[UIImageView alloc ]initWithFrame:CGRectMake(TSScaleW(15), TSScaleW(9), TSScaleW(12), TSScaleW(12))];
        _searchImg.image = [[UIImage imageNamed:@"搜索"] imageChangeColor:kMainTxtColor];
        _searchImg.centerY = _searchTextFiled.height/2.f;
    }
    return _searchImg;
}
-(BkHomePageView *)headerView{
    if (!_headerView) {
        _headerView = [[BkHomePageView alloc]init];
        _headerView.top = -_headerView.height-TSScaleW(10);
        WS(weakSelf);
        _headerView.selctItemBlock = ^(NSInteger index) {
            BkAgeListViewController *vc = [[BkAgeListViewController alloc]init];
          //  NSDictionary *dic = weakSelf.classify1Array[index];
            vc.currentIndex = index;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        _headerView.selctThemeBlock = ^(NSInteger index) {
            BkAgeListViewController *vc = [[BkAgeListViewController alloc]init];
            NSDictionary *dics = weakSelf.classify2Array[index];
            NSInteger ids = 0;
            for (int i = 0; i <weakSelf.classify1Array.count; i ++) {
                NSDictionary *dic = weakSelf.classify1Array[i];
                if ([dic[@"fid"] isEqual:dics[@"fid"]]) {
                    ids = i;
                    break;
                }
            }
            vc.currentIndex = ids;
            vc.secendName = dics[@"sid"];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        _headerView.seeMoreBlock = ^{
            BkAgeListViewController *vc = [[BkAgeListViewController alloc]init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        _headerView.reloadFrameBlock = ^{
            weakSelf.headerView.top = -weakSelf.headerView.height-TSScaleW(10);
            [weakSelf.collectionView addSubview:weakSelf.headerView];
            weakSelf.collectionView.contentInset = UIEdgeInsetsMake(weakSelf.headerView.height + TSScaleW(10), TSScaleW(15), 0, TSScaleW(15));
        };
        _headerView.bannerSelectBlock = ^(NSInteger selctIndex) {
            NSDictionary *dic = weakSelf.bannerArray[selctIndex];
            NSString *gid = dic[@"gid"];
            BkGoodsDetailViewController *vc = [[BkGoodsDetailViewController alloc]init];
          
            vc.gid =gid;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
    }
    return _headerView;
}
-(UICollectionView *)collectionView
{
    if (!_collectionView) {
        
           left = TSScaleW(15);
           space = TSScaleW(10);
           _row = _row?:4;
           UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
           layout.itemSize = CGSizeMake((self.view.width - left * 2 - space * (_row - 1))/_row - 1,TSScaleW(233));
           layout.minimumLineSpacing = space;
           layout.minimumInteritemSpacing = space;
           layout.scrollDirection = UICollectionViewScrollDirectionVertical;
           
           
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, TSScreenWidth, TSScreenHeight - Height_NavBar-Height_TabBar) collectionViewLayout:layout];
           _collectionView.delegate = self;
           _collectionView.dataSource = self;
           [_collectionView registerClass:[BkGoodsCollectionViewCell class] forCellWithReuseIdentifier:@"BkGoodsCollectionViewCell"];
        _collectionView.contentInset = UIEdgeInsetsMake(self.headerView.height + TSScaleW(10), left, 0, left);
           _collectionView.scrollEnabled = YES;
           self.collectionView.backgroundColor = kSubBacColor;
        //手势添加
        //此处给其增加长按手势，用此手势触发cell移动效果
        [self.view addSubview:_collectionView];
        [_collectionView addSubview:self.headerView];
        WS(weakSelf);
                     _collectionView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
                             [weakSelf headerRefresh];
                     }];
       
                     _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                             [weakSelf footerRefresh];
                     }];
    }
    return _collectionView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    BkGoodsDetailViewController *vc = [[BkGoodsDetailViewController alloc]init];
    NSDictionary *dic = self.dataArray[indexPath.row];
    vc.gid =dic[@"gid"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        
    BkGoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BkGoodsCollectionViewCell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = kWhiteColor;
    cell.dataDic = self.dataArray[indexPath.row];
    NSDictionary *dic = self.dataArray[indexPath.row];
    WS(weakSelf);
    cell.addCarBlock = ^{
        [weakSelf getaddgoodscarWithGid:dic[@"gid"]];
    };
    return cell;
}

#pragma mark ----添加购物车

-(void)getaddgoodscarWithGid:(NSString *)gid
{
    ///默认一个
    if (![self ifNoLoginGotoLoginAction]) {
        return;
    }
    NSDictionary * pamas = @{@"gid":gid,@"numbers":@"1"};
    [NetWorkTools postConJSONWithUrl:@"addgoodscar" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
       
        if (result.integerValue == 0) {
            
        }else{
            
        }
        [MBProgressHUD showError:resultNote];
    } fail:^(NSError *error) {
        
    }];
}
/** 图片滚动回调 */
-(void)collectListReq
{
    NSDictionary * pamas = @{@"nowPage":[NSString stringWithFormat:@"%ld",self.pageNum],@"pageCount":[NSString stringWithFormat:@"%d",kPage_Size]};
    [NetWorkTools postConJSONWithUrl:@"gettuigoodslist" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *array = responseObject[@"dataList"];
       
        if (result.integerValue == 0) {
            
            [self handleListWithModel:array];
        }else{
             [MBProgressHUD showError:resultNote];
        }
         
    } fail:^(NSError *error) {
        
    }];

}
#pragma mark - 上拉、下拉

-(void)headerRefresh
{
    self.pageNum = 1;
    [self collectListReq];
    
}

-(void)footerRefresh
{
    [self collectListReq];
}
-(void)endRefrash

{
   if (self.collectionView.mj_header.state == MJRefreshStateRefreshing) {
        [self.collectionView.mj_header endRefreshing];
    }
    
    if (self.collectionView.mj_footer.state == MJRefreshStateRefreshing) {
        [self.collectionView.mj_footer endRefreshing];
    }
}
-(void)handleListWithModel:(id )result
{
    [self endRefrash];

    NSArray *array = result;
    if (self.pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    [self.dataArray addObjectsFromArray:array];
    
   
    
     //[SSKJ_NoDataView showNoData:self.dataArray.count toView:self.collectionView offY:TSScaleW(10) message:@"您还没有数据哦~" imge:[UIImage imageNamed:@"nolikesimg"]];
    
    self.pageNum++;
    
    
    [self.collectionView reloadData];
    
    if (array.count != kPage_Size) {
        self.collectionView.mj_footer.state = MJRefreshStateNoMoreData;
    }else{

        self.collectionView.mj_footer.state = MJRefreshStateIdle;
    }
}



-(NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark ----轮播图网络请求
-(void)requstBannerRqust{
    [NetWorkTools postConJSONWithUrl:@"getbannerlist" parameters:@{} success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *dataList = responseObject[@"dataList"];
        if ([result integerValue] == 0) {
            self.bannerArray = dataList;
        }else{
            [MBProgressHUD showError:resultNote];
        }
    } fail:^(NSError *error) {
        
    }];
}
-(void)setBannerArray:(NSArray *)bannerArray{
    _bannerArray = bannerArray;
    self.headerView.bannerArray = _bannerArray;
}
#pragma mark ---一级分类请求
-(void)getclassify1listRqust{
    [NetWorkTools postConJSONWithUrl:@"getclassify1list" parameters:@{} success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *dataList = responseObject[@"dataList"];
        if ([result integerValue] == 0) {
            self.classify1Array = dataList;
        }else{
            [MBProgressHUD showError:resultNote];
        }
    } fail:^(NSError *error) {
        
    }];
}
-(void)setClassify1Array:(NSArray *)classify1Array{
    _classify1Array = classify1Array;
    [LXSaveUserInforTool sharedUserTool].classify1Array = _classify1Array;
    self.headerView.classify1Array = _classify1Array;
}
#pragma mark ----推荐二级分类

-(void)gettuiclassify2listRqust{
    [NetWorkTools postConJSONWithUrl:@"gettuiclassify2list" parameters:@{} success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *dataList = responseObject[@"dataList"];
        if ([result integerValue] == 0) {
            self.classify2Array = dataList;
        }else{
            [MBProgressHUD showError:resultNote];
        }
    } fail:^(NSError *error) {
        
    }];
}
-(void)setClassify2Array:(NSArray *)classify2Array
{
    _classify2Array = classify2Array;
    self.headerView.classify2Array = _classify2Array;
}

//-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//    NSString *contentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
//    if (contentString==nil) {
//        contentString = @"";
//    }
//    self.searchTextFiled.text = contentString;
//    [self headerRefresh];
//
//    return YES;
//}
#pragma mark ----获取未读消息数量

-(void)requstUnreadCount{
    //getmessnum
    [NetWorkTools postConJSONWithUrl:@"getmessnum" parameters:@{} success:^(id responseObject) {
       
        NSString *datastr = responseObject[@"datastr"];
//        if ([result integerValue] == 0) {
//            self.classify1Array = dataList;
//        }else{
//            [MBProgressHUD showError:resultNote];
//        }
        UIView *v = [self.messageBtn viewWithTag:22000000];
        if (v) {
            [v removeFromSuperview];
        }
        if (datastr.intValue !=0) {
           
            UILabel *unreadLabel = [TSWLTools allocLabel:datastr font:systemFont(TSScaleW(8)) textColor:kWhiteColor frame:CGRectMake(TSScaleW(30), TSScaleW(5), TSScaleW(18), TSScaleW(12)) textAlignment:(NSTextAlignmentCenter)];
            unreadLabel.tag = 22000000;
            [self.messageBtn addSubview:unreadLabel];
            unreadLabel.backgroundColor = kRedColor;
            unreadLabel.cornerRadius = unreadLabel.height/2.f;
           
            CGFloat w = [datastr boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, TSScaleW(10)) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:systemFont(TSScaleW(8))} context:nil].size.width;
            unreadLabel.width = w + TSScaleW(8);
            unreadLabel.left = self.messageBtn.width - unreadLabel.width;
        }
    } fail:^(NSError *error) {
        
    }];
}

@end
